<template>
  <div>
    <a-modal
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      :key="formKey"
    >
      <template #title> {{ modalTitle }} </template>
      <a-form
        :model="form"
        :style="{ width: '300px' }"
        auto-label-width
        ref="formRef"
      >
        <a-form-item
          field="cat_id"
          label="商品分类"
          :rules="[{ required: true, messgae: '商品分类是必须的' }]"
        >
          <a-select
            v-model="form.cat_id"
            placeholder="请选择商品分类"
            :disabled="modelType != 'add'"
          >
            <a-option
              v-for="item in props.categorySelectList"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          field="name"
          label="商品名称"
          :rules="[{ required: true, messgae: '商品名称是必须的' }]"
        >
          <a-input v-model="form.name" placeholder="请输入商品名称" />
        </a-form-item>
        <a-form-item
          field="img"
          label="商品图片"
          :rules="[{ required: true, messgae: '商品图片是必须的' }]"
        >
          <a-upload
            list-type="picture-card"
            :auto-upload="false"
            :multiple="false"
            :limit="1"
            image-preview
            v-model:file-list="form.img"
          />
        </a-form-item>
        <a-form-item
          field="price"
          label="商品价格"
          :rules="[{ required: true, messgae: '商品价格是必须的' }]"
        >
          <a-input-number v-model="form.price" :min="0" />
        </a-form-item>
        <a-form-item
          field="remark"
          label="商品备注"
          :rules="[{ required: true, messgae: '商品名称是备注的' }]"
        >
          <a-textarea
            placeholder="Please enter something"
            allow-clear
            v-model="form.remark"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue';
  import {
    addGoodsAPI,
    type AddGoods,
    detailsGoodsInfoAPI,
    editGoodsInfoAPI,
  } from '@/api/goods';
  import { Message } from '@arco-design/web-vue';

  const props = defineProps(['categorySelectList']);
  const base = import.meta.env.VITE_BASE_URLS;

  const emits = defineEmits(['resetFn']);

  const form = reactive<AddGoods>({
    cat_id: null,
    name: '',
    img: [],
    price: null,
    remark: '',
  });

  const goodId = ref(0);

  const formKey = ref(0);

  const formRef = ref();
  const visible = ref(false);
  const handleOk = async () => {
    try {
      //校验表单是否通过规则，没有通过就是一个数组有值，通过就没有值，不是undefined就return了，
      const validate = await formRef.value.validate();
      let formData = new FormData();
      formData.append('cate_id', `${form.cat_id}`);
      formData.append('name', `${form.name}`);
      //@ts-ignore
      formData.append('img', form.img);
      formData.append('price', `${form.price! * 100}`);
      formData.append('remark', `${form.remark}`);
      // 基本上表单都是validate()这个方法
      if (validate !== undefined) return;
      if (modelType.value == 'add') {
        const result = await addGoodsAPI(formData as unknown as AddGoods);
        Message.success('新增成功');
      } else {
        formData.append('id', `${goodId.value}`);
        await editGoodInfoFn(formData);
      }
      emits('resetFn');
      handleCancel();
    } catch (error) {
      Message.error('新增失败');
    }
  };
  const modalTitle = ref('');
  const modelType = ref('');
  // 给父级传递打开弹窗的方法
  const openModal = (type: string, id?: number) => {
    modelType.value = type;
    if (id) {
      goodId.value = id;
    }
    if (type == 'add') {
      modalTitle.value = '新增商品';
      form.cat_id = null;
    } else {
      modalTitle.value = '编辑商品';
      detailsGoodsInfoFn(id as number);
    }
    visible.value = true;
  };

  // 上传图片内容改变时
  const changeImage = (e: any) => {
    form.img = e[0].file;
  };
  // 取消
  const handleCancel = () => {
    visible.value = false;
    form.cat_id = 0;
    form.name = '';
    form.img = [];
    form.price = null;
    form.remark = '';
    formKey.value++; //这个是直接强制表带更新，arco也有其他方式清除，暂时没有时间就不写那个了
  };

  // 获取商品详情
  const detailsGoodsInfoFn = async (id: number) => {
    try {
      const result = (await detailsGoodsInfoAPI(id)).data;
      form.name = result.data.name;
      form.price = result.data.price * 0.01;
      form.remark = result.data.remark;
      form.cat_id = result.data.cate_id;
      form.img.push(base + result.data.img_url);
    } catch (error) {
      Message.error('获取商品详情失败请重新尝试');
    }
  };

  const editGoodInfoFn = async (formData: FormData) => {
    try {
      await editGoodsInfoAPI(formData);
      Message.success('编辑商品信息成功');
    } catch (error) {
      Message.error('编辑商品信息失败请重新尝试');
    }
  };

  defineExpose({ openModal });
</script>

<style lang="scss" scoped></style>
